﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web.Mvc;
using BookShop.BLL;
using BookShop.DTO;
using BookShop.Library.Constant;
using BookShop.Site.Models;
using PagedList;
using BookShop.Library.Common;

namespace BookShop.Site.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult About()
        {
            return View();
        }

        public ActionResult AllCategory()
        {
            var model = new ListCategoryPublisherAuthor<Category>
            {
                BestsellerBooks = BookService.GetBestSellers(null, TimePeriod.Year),
                Categories = CategoryService.GetAll()
            };
            model.ModelList = model.Categories;
            return View(model);
        }

        public ActionResult AllAuthor()
        {
            var model = new ListCategoryPublisherAuthor<Author>
            {
                BestsellerBooks = BookService.GetBestSellers(null, TimePeriod.Year),
                Categories = CategoryService.GetAll(),
                ModelList = AuthorService.GetAll()
            };
            return View(model);
        }

        public ActionResult AllPublisher()
        {
            var model = new ListCategoryPublisherAuthor<Publisher>
            {
                BestsellerBooks = BookService.GetBestSellers(null, TimePeriod.Year),
                Categories = CategoryService.GetAll(),
                ModelList = PublisherService.GetAll()
            };
            return View(model);
        }

        public ActionResult BestsellerPage(int page = 1, int pageSize = 12)
        {
            var model = new HomeViewModel
            {
                BestSellerBookList = BookService.UpdateNotMappedField(BookService.GetBestSellers(100, TimePeriod.Year)),
                CategoryList = CategoryService.GetAll(),
                HasPriceSlider = false
            };
            var totalCount = model.BestSellerBookList.Count;
            model.BestSellerBookList = model.BestSellerBookList.Skip((page - 1) * pageSize).Take(pageSize).ToList();
            ViewBag.SearchPageSize = pageSize;
            ViewBag.PageList = new StaticPagedList<Book>(model.BestSellerBookList, page, pageSize, totalCount);
            return View(model);
        }

        public ActionResult ContactUs()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ContactUs(string fullName, string email, string message)
        {
            try
            {
                var mail = new MailMessage(email.Trim(), CommonFunction.GetConfigValue("MailUsername"));
                var smtp = new SmtpClient(CommonFunction.GetConfigValue("MailServer"));
                mail.Subject = "Ý kiến khách hàng";
                if (!string.IsNullOrWhiteSpace(fullName))
                {
                    mail.Subject += ": " + fullName;
                }
                mail.Body = message;
                smtp.Port = int.Parse(CommonFunction.GetConfigValue("SendMailPort"));
                smtp.Credentials = new NetworkCredential(CommonFunction.GetConfigValue("MailUsername"),
                    CommonFunction.GetConfigValue("MailPassword"));
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
            catch (Exception)
            {
                return RedirectToAction("Error");
            }
            return RedirectToAction("ContactSent");
        }

        public ActionResult ContactSent()
        {
            return View();
        }

        public ActionResult Error()
        {
            return View();
        }

        public ActionResult Index()
        {
            var model = new HomeViewModel
            {
                NewBookList = BookService.UpdateNotMappedField(BookService.GetNewest(10)),
                BestSellerBookList = BookService.UpdateNotMappedField(BookService.GetBestSellers(5, TimePeriod.Year)),
                TopRatedBookList = BookService.UpdateNotMappedField(BookService.GetTopRated(5)),
                CategoryList = CategoryService.GetAll()
            };
            return View(model);
        }

        [ValidateInput(false)]
        public ActionResult ProductPage(string title, int? categoryId, int? authorId, int? publisherId,
            string fromPrice, string toPrice, int sort = SortType.NameAsc, int page = 1, int pageSize = 12)
        {
            int totalBookCount;
            var model = new HomeViewModel
            {
                BestSellerBookList = BookService.UpdateNotMappedField(BookService.GetBestSellers(5, TimePeriod.Year)),
                CategoryList = CategoryService.GetAll(),
                TopRatedBookList = BookService.UpdateNotMappedField(BookService.GetTopRated(10)),
                AllBookList =
                    BookService.UpdateNotMappedField(BookService.Search(null, title, categoryId, authorId, publisherId,
                        fromPrice, toPrice, BookStatus.Active, page, pageSize, out totalBookCount))
            };
            switch (sort)
            {
                case SortType.NameAsc:
                    model.AllBookList = model.AllBookList.OrderBy(b => b.Title).ToList();
                    break;
                case SortType.PriceAsc:
                    model.AllBookList = model.AllBookList.OrderBy(b => b.Price).ToList();
                    break;
                case SortType.RatePointAsc:
                    model.AllBookList = model.AllBookList.OrderBy(b => b.AverageRatePoint).ToList();
                    break;
                case SortType.NameDesc:
                    model.AllBookList = model.AllBookList.OrderByDescending(b => b.Title).ToList();
                    break;
                case SortType.PriceDesc:
                    model.AllBookList = model.AllBookList.OrderByDescending(b => b.Price).ToList();
                    break;
                case SortType.RatePointDesc:
                    model.AllBookList = model.AllBookList.OrderByDescending(b => b.AverageRatePoint).ToList();
                    break;
            }
            model.HasPriceSlider = true;
            if (categoryId.HasValue)
            {
                ViewBag.SearchCategoryName = ((CategoryService.GetById(categoryId.Value) ?? new Category { Name = string.Empty }).Name);
            }
            ViewBag.PageList = new StaticPagedList<Book>(model.AllBookList, page, pageSize, totalBookCount);
            ViewBag.SearchTitle = title ?? string.Empty;
            ViewBag.SearchSort = sort;
            ViewBag.SearchAuthorId = authorId.ToString();
            ViewBag.SearchCategoryId = categoryId.ToString();
            ViewBag.SearchPublisherId = publisherId.ToString();
            ViewBag.SearchMinPrice = fromPrice ?? string.Empty;
            ViewBag.SearchMaxPrice = toPrice ?? string.Empty;
            ViewBag.SearchPageSize = pageSize;
            ViewBag.TotalCount = totalBookCount;
            return View(model);
        }

        public ActionResult SalePage(int page = 1, int pageSize = 12)
        {
            var model = new SalePageModel
            {
                Books = BookService.UpdateNotMappedField(BookService.GetDiscount(null)),
                Categories = CategoryService.GetAll()
            };
            var totalCount = model.Books.Count;
            model.Books = model.Books.Skip((page - 1) * pageSize).Take(pageSize).ToList();
            ViewBag.SearchPageSize = pageSize;
            ViewBag.PageList = new StaticPagedList<Book>(model.Books, page, pageSize, totalCount);
            return View(model);
        }

        public JsonResult GetAllCategory(int? count)
        {
            return Json(count.HasValue ? CategoryService.GetAll().Take(count.Value).ToList() : CategoryService.GetAll());
        }

        public JsonResult GetAllPublisher(int? count)
        {
            return Json(count.HasValue ? PublisherService.GetAll().Take(count.Value).ToList() : PublisherService.GetAll());
        }

        public JsonResult GetOnSaleBook(int? count)
        {
            var bookList = BookService.GetDiscount(count).ToList();
            return Json(bookList);
        }

        public JsonResult GetAllAuthor(int? count)
        {
            return Json(count.HasValue ? AuthorService.GetAll().Take(count.Value).ToList() : AuthorService.GetAll());
        }
    }
}
